package org.spider.core.executor.function.functionExtension;

import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.spider.api.annotation.Comment;
import org.spider.api.annotation.Example;
import org.spider.api.annotation.Return;
import org.spider.api.executor.FunctionExtension;
import org.spider.core.utils.ExtractUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class StringFunctionExtension implements FunctionExtension {

	@Override
	public Class<?> support() {
		return String.class;
	}	

	@Comment("根据xpath在String变量中查找")
	@Example("${strVar.xpath('//title/text()')}")
	@Return({Element.class,String.class})
	public static String xpath(String source,String xpath){
		return ExtractUtils.getValueByXPath(element(source), xpath);
	}
	
	@Comment("根据xpath在String变量中查找")
	@Example("${strVar.xpaths('//a/@href')}")
	public static List<String> xpaths(String source,String xpath){
		return ExtractUtils.getValuesByXPath(element(source), xpath);
	}

	@Comment("将String变量转为Element对象")
	@Example("${strVar.element()}")
	public static Element element(String source){
		return Parser.xmlParser().parseInput(source,"");
	}

	@Comment("根据正则表达式提取String中的内容")
	@Example("${strVar.regx('<title>(.*?)</title>')}")
	public static String regx(String source,String pattern){
		return ExtractUtils.getFirstMatcher(source, pattern, true);
	}
}
